<?php

namespace Framework\Foundation\Container;

use Framework\Foundation\Container\Exceptions\NotFoundException;
use Psr\Container\ContainerInterface;

class Container implements ContainerInterface
{
    //创建静态私有的变量保存该类对象
    protected static $instance;

    protected function __construct()
    {
    }

    protected function __clone()
    {
    }

    public static function instance()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }


    private $objects = [];
    private $aliases = [];

    public function get($id)
    {
        if (in_array($id, $this->aliases)) {
            $id = $this->getAliasId($id);
        }

        if (isset($this->objects[$id])) {
            return $this->objects[$id];
        }

        if (isset($this->aliases[$id])) {
            return $this->objects[$id] = new $this->aliases[$id];
        }

        if (class_exists($id)) {
            return $this->objects[$id] = new $id;
        }

        new NotFoundException("not found in container");
    }

    public function has($id)
    {
        if (isset($this->objects[$id])) {
            return true;
        }
        if (isset($this->aliases[$id])) {
            return true;
        }

        return false;
    }

    public function set($id, $object)
    {
        $this->objects[$id] = $object;
        return true;
    }

    public function setAlias($id, $name)
    {
        $this->aliases[$id] = $name;
        return true;
    }

    public function setAliases($aliases)
    {
        $this->aliases = $aliases;
        return true;
    }

    private function getAliasId(string $searchName)
    {
        foreach ($this->aliases as $id => $name) {
            if ($name == $searchName) {
                return $id;
            }
        }
        return null;
    }
}
